/**
 * @Author: Liu, Yunfeng
 * @DateTime: 2021/3/3 23:21
 * @Description: 给你两个二进制字符串，返回它们的和（用二进制表示）。输入为 非空 字符串且只包含数字 1 和 0。
 */
public class addBinary {
    public static String addBinary(String a, String b) {
        int lengthA = a.length();
        int lengthB = b.length();
        StringBuilder c = new StringBuilder();
        int i = 1;
        char plus = '0';
        char tmp = '0';
        while (lengthA - i >= 0 && lengthB - i >= 0) {
            if (a.charAt(lengthA - i) == '1' && b.charAt(lengthB - i) == '1') {
                tmp = '0';
                c.append(tmp == plus ? '0' : '1');
                plus = '1';
            } else if (a.charAt(lengthA - i) == '0' && b.charAt(lengthB - i) == '0') {
                tmp = '0';
                c.append(tmp == plus ? '0' : '1');
                plus = '0';
            } else {
                tmp = '1';
                c.append(tmp == plus ? '0' : '1');
                plus = plus=='1'?'1':'0';
            }
            i++;
        }
        String d = "";
        if (lengthA > lengthB) {
            d = a.substring(0, lengthA - lengthB);
        } else {
            d = b.substring(0, lengthB - lengthA);
        }
        for (int j = d.length() - 1; j >= 0; j--) {
            if (d.charAt(j) == '1' && plus == '1') {
                c.append(0);
                plus = '1';
            } else {
                c.append(d.charAt(j) == plus ? 0 : 1);
                plus = '0';
            }
        }
        if(plus == '1'){
            c.append('1');
        }
        return c.reverse().toString();
    }

    public static void main(String[] Args) {
        String a = "1010";
        String b = "1011";
        System.out.println(addBinary(a, b));
    }
}
